package com.project.homework4_8.service.impl;

import com.project.homework4_8.bean.LogBean;
import com.project.homework4_8.dao.ILogDao;
import com.project.homework4_8.dao.impl.LogDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class ProxyService implements InvocationHandler {

    private ILogDao dao = new LogDaoImpl();

    private Object targetObj;

    public ProxyService(Object targetObj) {
        this.targetObj = targetObj;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(
                targetObj.getClass().getClassLoader(),
                targetObj.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String e = (String) method.invoke(targetObj,args);
        String info = "";
        Class c = targetObj.getClass();
        info += c.getName() + "类在";
        String time = DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalTime.now());
        info += time + ",执行" + method.getName() + "方法时，抛出";
        if (e!=null){
            info += e + "异常";
            dao.add(new LogBean(info));
        }
        return null;
    }
}
